import { useAnvilCodeStore } from '../../store/modules/code';
import { NavigationGuardNext, RouteLocationNormalizedGeneric, RouteLocationNormalizedLoadedGeneric, useRouter } from 'vue-router';
import defaultSettings from '@/settings';

export const useAnvilCode = () => {
  const { setPageId } = useAnvilCodeStore();

  // 根据路由参数获取pageId
  const setAnvilPageId = (to) => {
    console.log('currentRoute', to);
    const { query, params } = to;
    if (params && params.pageId) {
      setPageId(params.pageId as string);
    } else if (query && query.pageId) {
      setPageId(query.pageId as string);
    }
  };

  // 在路由中携带from参数用于记录页面从哪里跳转而来
  const setRouterFrom = (to: RouteLocationNormalizedGeneric, from: RouteLocationNormalizedLoadedGeneric, next: NavigationGuardNext) => {
    if (to.query.from) {
      next();
    } else {
      // 需要处理from参数无限拼接的问题，目前保留两层from,寻找第三个from所在位置
      let fromPath = '';
      const targetFromIdx = findStrIndex(from.fullPath, 'from', 2);
      if (targetFromIdx !== -1) {
        fromPath = encodeURIComponent(from.fullPath.substring(0, targetFromIdx));
      } else {
        fromPath = encodeURIComponent(from.fullPath);
      }

      console.log('fromPath', fromPath);
      const newTo = {
        ...to,
        query: {
          ...to.query,
          from: fromPath
        }
      };
      next(newTo);
    }
  };

  // 处理低代码页面的路由转换
  const getLowCodePageRouter = (url: string) => {
    // 寻找低代码页面标志的位置
    const codeRouterSuffix = defaultSettings.codeRouterSuffix;
    const signIndex = url.indexOf(codeRouterSuffix);
    if (signIndex > -1) {
      // const menuPath = url.substring(0, signIndex);
      const menuHash = url.substring(signIndex + codeRouterSuffix.length);
      const newUrl = location.origin + location.pathname + menuHash;
      return {
        menuHash,
        url: newUrl
      };
    } else {
      return { url };
    }
  };

  // 处理低代码相关页面跳转
  const handleLowCodePageRouter = (to: RouteLocationNormalizedGeneric, from: RouteLocationNormalizedLoadedGeneric, next: NavigationGuardNext) => {
    const { fullPath } = to;
    const { menuHash } = getLowCodePageRouter(fullPath);
    if (menuHash) {
      console.log('hash', menuHash);
      next(menuHash);
    } else {
      next();
    }
  };

  // 找到同一个字符串第n次出现的位置
  const findStrIndex = (str: string, targetStr: string, time: number) => {
    let start = 0;
    start = str.indexOf(targetStr, start);
    let num = 0;
    while (start !== -1 && num !== time) {
      console.log(start); // 打印字符串出现的位置
      num++; // 每出现一次 次数加一
      start = str.indexOf(targetStr, start + 1); // 从字符串出现的位置的下一位置开始继续查找
    }

    return start;
  };

  // 将低代码填报页面的路由映射全部缓存下来
  const cacheLowCodePageRouter = (routers: RouteLocationNormalizedGeneric[], map?: any) => {
    const routerMap = map ?? {};
    routers.map((r: RouteLocationNormalizedGeneric) => {
      const { path } = r;
      const codeRouterSuffix = defaultSettings.codeRouterSuffix;
      if (path.includes(codeRouterSuffix)) {
        let hash = '';
        hash = path.replace(`/${codeRouterSuffix}`, '').replace(codeRouterSuffix, '');
        routerMap[hash] = {
          path,
          title: r.meta.title,
          icon: r.meta.icon
        };
      }
      if (r.children && r.children.length) {
        cacheLowCodePageRouter(r.children, routerMap);
      }
    });
    // 最外层函数执行逻辑
    if (!map) {
      console.log('routerMap', routerMap);
      localStorage.setItem(`lowCodeRouterCache_${location.pathname}`, JSON.stringify(routerMap));
    }
  };

  const getLowCodeRouterCache = (path: string) => {
    const routerMapJSON = localStorage.getItem(`lowCodeRouterCache_${location.pathname}`);
    if (routerMapJSON) {
      const routerMap = JSON.parse(routerMapJSON);
      if (routerMap[path]) {
        return routerMap[path];
      }
    } else {
      return null;
    }
  };

  return {
    setAnvilPageId,
    setRouterFrom,
    handleLowCodePageRouter,
    cacheLowCodePageRouter,
    getLowCodeRouterCache
  };
};
